package com.dbsop.domain.transport.res;

import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.script.Script;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class XContentBuilderUtils {


    public static XContentBuilder getXContentBuilderByMap(Map<String, Object> params) {
        try {
            XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().startObject();
            params.forEach((fieldName, value) -> {
                try {
                    xContentBuilder.field(fieldName, value);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            return xContentBuilder.endObject();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static ToXContent.Params getParams(Map<String, Object> paramMap) {
        Map<String, String> map = new HashMap<String, String>();
        paramMap.forEach((s, o) -> {
            if (o == null) map.put(s, null);

            if (o != null) map.put(s, o.toString());
        });
        return new ToXContent.MapParams(map);
    }


    public static Script getScript(Map<String, Object> paramMap) {
        StringBuffer buffer = new StringBuffer();
        paramMap.forEach((key, value) -> {
            if (value == null)buffer.append(";ctx._source." + key + "=null");
            if (value != null)buffer.append(";ctx._source." + key + "="+value);
        });
        String scriptString = buffer.toString().substring(1, buffer.length());
        System.out.println(" update script:"+ scriptString);
        return new Script(scriptString);
    }
}
